//~ Project: TheGenerator File: GeneratorFactory.groovy Created date: Oct 24, 2011
package com.ii2d.tg.generators

import groovy.lang.GroovyClassLoader

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

class GeneratorFactory {
	
	private static final Log LOG = LogFactory.getLog(GeneratorFactory.class)
	
	public static final String DEFAULT_PACKAGE = "com.ii2d.tg.generators"
	
	String basePackage
	GroovyClassLoader classLoader
	
	public GeneratorFactory(){
		this(null)
	}
	public GeneratorFactory(String basePackage) {
		this.basePackage = basePackage?: DEFAULT_PACKAGE
		classLoader = new GroovyClassLoader(this.class.classLoader)
	}
	
	public Generator newInstance(String generatorName, args) {
		try {
			String className = "${basePackage}.${generatorName[0].toUpperCase()}${generatorName[1..-1]}Generator"
			Class<?> clazz = classLoader.loadClass(className)
//			if(!clazz) throw new ClassNotFoundException(className) //Not need
			return clazz.newInstance(args)
		} catch (ClassNotFoundException e) {
			LOG.error("Cannot found the generator ${e.getMessage()}")
		}
	}
	
	public Generator newInstance(String generatorName) {
		return this.newInstance(generatorName, null)
	}
	
	public void setBasePackage(String p) {
		this.basePackage = p !=~ /\.$/ ?: p[0, -2]
	}
	
	String toString() {
		"class: ${this.class}, base package: ${basePackage}"
	}
}
